package com.ndood.authenticate.app;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.social.security.SpringSocialConfigurer;

import com.ndood.authenticate.app.handler.AppAuthenticationFailureHandler;
import com.ndood.authenticate.app.handler.AppAuthenticationSuccessHandler;
import com.ndood.authenticate.app.openid.OpenIdAuthenticationSecurityConfig;
import com.ndood.core.authentication.mobile.SmsCodeAuthenticationSecurityConfig;
import com.ndood.core.authorize.AuthorizeConfigManager;
import com.ndood.core.validate.code.ValidateCodeSecurityConfig;

/**
 * oauth2资源服务器配置
 * 加了这个等于把app定义成资源服务器，访问资源的时候要先通过认证
 */
@Configuration
@EnableResourceServer
public class AppResourceServerConfig extends ResourceServerConfigurerAdapter{
	
	@Autowired
	private AppAuthenticationSuccessHandler appAuthenticationSuccessHandler;
	
	@Autowired
	private AppAuthenticationFailureHandler appAuthenticationFailureHandler;
	
	@Autowired
	private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;
	
	@Autowired
	private SpringSocialConfigurer springSocialSecurityConfig;
	
	@Autowired
	private ValidateCodeSecurityConfig validateCodeSecurityConfig;
	
	@Autowired
	private OpenIdAuthenticationSecurityConfig openIdAuthenticationSecurityConfig;
	
	@Autowired
	private AuthorizeConfigManager authorizeConfigManager;
	
	/**
	 * 配置http
	 */
	@Override
	public void configure(HttpSecurity http) throws Exception {

		http
			.apply(validateCodeSecurityConfig)
				.and()
			.apply(smsCodeAuthenticationSecurityConfig)
				.and()
			.apply(springSocialSecurityConfig)
				.and()
			
			.formLogin()
				.loginPage("/authentication/require")
				.loginProcessingUrl("/authentication/form")
				.successHandler(appAuthenticationSuccessHandler)
				.failureHandler(appAuthenticationFailureHandler)
				.and()
			
			.apply(openIdAuthenticationSecurityConfig)
					.and()			
				
			.csrf().disable();
		
		// 调用公共的权限管理配置
		authorizeConfigManager.config(http.authorizeRequests());
	}	
}
